package com.tuuzed.android.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.tuuzed.android.ui.internal.CircleView;

public class BottomTabItem extends FrameLayout {
    private String mLabel;
    @ColorInt
    private int mLabelColor;
    @ColorInt
    private int mLabelCheckedColor;
    private Drawable mIcon;
    private Drawable mIconChecked;
    private ImageView mIvIcon;
    private CircleView mBadge;
    private TextView mTvLabel;
    private boolean mIsChecked = false;

    public BottomTabItem(@NonNull Context context) {
        this(context, null);
    }

    public BottomTabItem(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomTabItem(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BottomTabItem);
        mLabel = a.getString(R.styleable.BottomTabItem_bti_label);
        mLabelColor = a.getColor(R.styleable.BottomTabItem_bti_labelColor, Color.DKGRAY);
        mLabelCheckedColor = a.getColor(R.styleable.BottomTabItem_bti_labelCheckedColor, Color.BLACK);
        mIcon = a.getDrawable(R.styleable.BottomTabItem_bti_icon);
        mIconChecked = a.getDrawable(R.styleable.BottomTabItem_bti_iconChecked);
        if (mIconChecked == null) mIconChecked = mIcon;
        a.recycle();

        inflate(context, R.layout.bottom_tab_item, this);
        initView();
    }

    private void initView() {
        mIvIcon = findViewById(R.id.iv_icon);
        mBadge = findViewById(R.id.badge);
        mTvLabel = findViewById(R.id.tv_label);

        // checked == false
        mTvLabel.setText(mLabel);
        mTvLabel.setTextColor(mLabelColor);
        mIvIcon.setImageDrawable(mIcon);

        enableBadge(false);
    }

    void checked(boolean isChecked) {
        if (mIsChecked == isChecked) return;
        mIsChecked = isChecked;
        if (mIsChecked) {
            mTvLabel.setTextColor(mLabelCheckedColor);
            mIvIcon.setImageDrawable(mIconChecked);
        } else {
            mTvLabel.setTextColor(mLabelColor);
            mIvIcon.setImageDrawable(mIcon);
        }
    }

    boolean isChecked() {
        return mIsChecked;
    }

    void enableBadge(boolean enable) {
        if (enable) {
            mBadge.setVisibility(VISIBLE);
        } else {
            mBadge.setVisibility(INVISIBLE);
        }
    }
}
